var crypto = require('../cryptojs/cryptojs.js').Crypto;
function WXBizDataCrypt(appId, sessionKey) {
  this.appId = appId
  this.sessionKey = sessionKey
}
WXBizDataCrypt.prototype.decryptData = function (encryptedData, iv) {
  encryptedData = encryptedData.replace(/ /g, '+')
  iv = iv.replace(/ /g, '+')
  var encryptedData = crypto.util.base64ToBytes(encryptedData)
  var sessionKey = crypto.util.base64ToBytes(this.sessionKey);
  var iv = crypto.util.base64ToBytes(iv);
  var mode = new crypto.mode.CBC(crypto.pad.pkcs7);
  try {
    // 解密
    var bytes = crypto.AES.decrypt(encryptedData, sessionKey, {
      asBpytes: true,
      iv: iv,
      mode: mode
    });
    var decryptResult = JSON.parse(bytes);

  } catch (err) {
    console.log('err :>> ', err);
    throw new Error('Illegal Buffer1', err)
  }

  if (decryptResult.watermark.appid !== this.appId) {
    throw new Error('Illegal Buffer2')
  }

  return decryptResult
}

module.exports = WXBizDataCrypt
